package com.dcrzl.gazgmh.common.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @version 1.0
 * @Description 加密工具类
 * @date 2020/12/25 14:37
 * @author: (ssh)
 */
@Slf4j
public class EncryptionUtil {
    /**
     * @param algorithm 加密方式
     * @return
     */
    public static String getEncryption(String algorithm, String data) {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] bytes = messageDigest.digest(data.getBytes());
            for (byte b : bytes) {
                sb.append(Integer.toHexString((b >> 4) & 0xf));
                sb.append(Integer.toHexString(b & 0xf));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }


    /**
     * 获取加密后信息
     *
     * @param plainText 明文
     * @return 加密后信息
     */
    public static String getEncryptDESData(String plainText, String key) {
        DES des =SecureUtil.des(SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(),
                key.getBytes()).getEncoded());
        return des.encryptHex(plainText);
    }

    /**
     * 获取解密后信息
     *
     * @param cipherText 密文
     * @return 解密后信息
     */
    public static String getDecryptDESData(String cipherText,String key) {
        DES des =SecureUtil.des(SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), key.getBytes()).getEncoded());
        return des.decryptStr(cipherText);
    }

    public static void main(String[] args) {
        String str = "123456";
        String EncryptStr = getEncryptDESData(str,"11111111h11111111");
        log.info("加密后数据为,EncryptStr:{}", EncryptStr);
        log.info("解密后数据为,str:{}", getDecryptDESData(EncryptStr,"11111111h11111111"));
    }


}
